package data.structure.linear.heap;

import data.structure.linear.heap.printer.BinaryTreeInfo;

import java.util.Comparator;

public class BinaryHeap<E> extends AbstractHeap<E> implements BinaryTreeInfo {

    private static final int DEFAULT_CAPACITY = 10;
    private E[] elements;

    public BinaryHeap(E[] elements, Comparator<E> comparator) {
        super(comparator);

        if (elements == null || elements.length == 0) {
            this.elements = (E[]) new Object[DEFAULT_CAPACITY];
        } else {
            int capaticy = Math.max(elements.length, DEFAULT_CAPACITY);
            this.elements = (E[]) new Object[capaticy];
            size = elements.length;
            for (int i = 0; i < size; i++) {
                this.elements[i] = elements[i];
            }
            // 原地建堆
            heapify();
        }
    }

    public BinaryHeap(E[] elements) {
        this(elements, null);
    }

    public BinaryHeap() {
        this(null, null);
    }

    public BinaryHeap(Comparator<E> comparator) {
        this(null, comparator);
    }


    // 批量建堆
    private void heapify() {
        // 自上而下的上滤
//		for (int i = 1; i < size; i++) {
//			siftUp(i);
//		}

        // 自下而上的下滤
        for (int i = (size >> 1) - 1; i >= 0; i--) {
            siftDown(i);
        }
    }

    // 删除
    @Override
    public void clear() {
        for (int i = 0; i < size; i++) {
            elements[i] = null;
        }
        size = 0;
    }

    // 新增 加到末尾   再上溢
    @Override
    public void add(E element) {
        elementNotNullCheck(element);
        ensureCapacity(size + 1);
        elements[size++] = element;
        siftUp(size - 1);
    }

    // 拿到堆顶
    @Override
    public E get() {
        // 校验堆是否有元素
        emptyCheck();
        return elements[0];
    }

    // 删除堆顶
    // 1.拿到堆顶
    // 2.size -1
    // 3.数组末尾元素值覆盖堆顶元素值
    // 4.数组末尾元素赋值为空
    // 5.下溢
    // 6.返回删除元素
    @Override
    public E remove() {
        emptyCheck();
        E root = elements[0];

        int lastIndex = --size;
        elements[0] = elements[lastIndex];
        elements[lastIndex] = null;

        siftDown(0);
        return root;
    }

    // 替换首位
    @Override
    public E replace(E element) {
        elementNotNullCheck(element);

        E root = null;
        if (size == 0) {
            elements[size++] = element;
//            elements[0] = element;
//            size++;
        } else {
            root = elements[0];
            elements[0] = element;
            siftDown(0);
        }
        return root;
    }

    // 元素空判断
    private void elementNotNullCheck(E element) {
        if (element == null) {
            throw new IllegalArgumentException("element must not be null");
        }
    }

    // 扩容判断
    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) return;

        // 新容量为旧容量的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[i];
        }
        elements = newElements;
    }

    // 空堆判断
    private void emptyCheck() {
        if (size == 0) {
            throw new IndexOutOfBoundsException("Heap is empty");
        }
    }


    // 上溢
    private void siftUp(int index) {
        E element = elements[index];
        // 如果 node ≤ 父节点，或者 node 没有父节点 结束循环
        while (index > 0) {
            int parentIndex = (index - 1) >> 1;
            E parentElement = elements[parentIndex];
            if (compare(element, parentElement) <= 0) {
                break;
            }

            // 将父索引值 赋值到 index索引
            elements[index] = parentElement;
            // 将父索引 赋值到 循环比较索引
            index = parentIndex;
        }

        elements[index] = element;
    }

    // 下溢
    private void siftDown(int index) {
        E element = elements[index];
        int half = size >> 1;
        // 第一个叶子节点的索引 == 非叶子节点的数量
        // index < 第一个叶子节点的索引
        // 必须保证index位置是非叶子节点
        while (index < half) {
            // 默认为左子节点跟它进行比较
            int childIndex = (index << 1) + 1;
            E child = elements[childIndex];

            // 右子节点
            int rightIndex = childIndex + 1;
            if (rightIndex < size && compare(elements[rightIndex], child) > 0) {
                child = elements[childIndex = rightIndex];
            }

            if (compare(element, child) >= 0) break;

            // 将子节点存放到index位置
            elements[index] = child;
            // 重新设置index
            index = childIndex;

        }
        elements[index] = element;
    }


    @Override
    public Object root() {
        return 0;
    }

    @Override
    public Object left(Object node) {
        int index = ((int) node << 1) + 1;
        return index >= size ? null : index;
    }

    @Override
    public Object right(Object node) {
        int index = ((int) node << 1) + 2;
        return index >= size ? null : index;
    }

    @Override
    public Object string(Object node) {
        return elements[(int) node];
    }
}
